/**
 * <pre>
 * Title: 		ArticleGroupController.java
 * Project: 	MSOSS
 * Author:		pengfangliang
 * Create:	 	2012-8-7 上午10:14:25
 * Copyright: 	Copyright (c) 2012
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.itfinoss.controller.article;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.en.ArticleGroupType;
import com.hengpeng.itfinbase.persist.Article;
import com.hengpeng.itfinbase.persist.ArticleGroup;
import com.hengpeng.itfinbase.persist.ArticleGroupEx;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.controller.vo.ArticleGroupVo;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * 文章分组管理
 * </pre>
 * 
 * @author pengfangliang
 * @version 1.0, 2012-8-7
 */
@Controller
@RequestMapping("/gm")
public class ArticleGroupController extends BaseController {
    @Autowired
    private ServiceFactory serviceFactory;

    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public ModelAndView preCreate() {
        ModelAndView modelAndView = new ModelAndView("/article/group/detail");
        modelAndView.addObject("group", new ArticleGroupVo());
        return modelAndView;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String add(HttpServletRequest request, ModelMap map, String articleGroupType) {
        ArticleGroup model = new ArticleGroup();
        model.setName(request.getParameter("name"));
        model.setRemark(request.getParameter("remark"));
        model.setVersion(Long.parseLong(request.getParameter("version")));
        model.setArticleGroupType((articleGroupType == null || articleGroupType.equals("")) ? null : ArticleGroupType
                .valueOf(articleGroupType));

        if (model.getArticleGroupType() != null) {
            if (serviceFactory.getArticleGroupSerivce().getArticleByGroupType(
                    ArticleGroupType.valueOf(articleGroupType)) != null) {
                return PageHandlerUtil.returnError(map, "新闻类型{" + model.getArticleGroupType().getText()
                        + "}对应的新闻不能有重复!");
            }
        }

        try {
            ServiceResult<ArticleGroup> result = null;
            String articles = request.getParameter("articleIds");
            if (!StringHelper.isEmpty(articles)) {
                String[] articleArray = articles.split(",");
                Set<ArticleGroupEx> exSet = new HashSet<ArticleGroupEx>();
                for (String articleId : articleArray) {
                    List<Article> article = serviceFactory
                            .getArticleService()
                            .findArticle(Long.parseLong(articleId), null, null, null, null, null, null, null, null,
                                    null, null, null, null, null, Constant.G_INT_DATA_INVALID,
                                    Constant.G_INT_DATA_INVALID, null).getResults();
                    // if (serviceFactory.getPersistService().get(Article.class,
                    // Long.valueOf(articleId)) == null)
                    if (article == null || article.isEmpty() || article.size() <= 0) {
                        return PageHandlerUtil.returnError(map, "新闻ID{" + articleId + "}对应的新闻不存在!");
                    }
                    ArticleGroupEx ex = new ArticleGroupEx();
                    ex.setArticleId(Long.valueOf(articleId));
                    // ex.setGroupId(result.getReturnValue().getId());
                    exSet.add(ex);
                }
                result = serviceFactory.getArticleGroupSerivce().save(model);
                for (ArticleGroupEx articleGroupEx : exSet) {
                    articleGroupEx.setGroupId(result.getReturnValue().getId());
                }
                serviceFactory.getPersistService().saveAllObject(exSet);
            }
            if (null == result) {
                result = serviceFactory.getArticleGroupSerivce().save(model);
            }
            return returnSuccess(map, result, "/gm/list");
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
            return returnError(map, "请检查新闻ID是否输入了非法数字!");
        } catch (Exception ex) {
            ex.printStackTrace();
            return returnError(map, ex);
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    public String update(@PathVariable long id, HttpServletRequest request, ModelMap map, String articleGroupType) {
        ArticleGroup model = serviceFactory.getArticleGroupSerivce().get(id).getReturnValue();
        if (model == null) {
            return PageHandlerUtil.returnError(map, "分组ID{" + id + "}对应的分组不存在!");
        }
        model.setName(request.getParameter("name"));
        model.setRemark(request.getParameter("remark"));
        model.setVersion(Long.parseLong(request.getParameter("version")));
        model.setArticleGroupType((articleGroupType == null || articleGroupType.equals("")) ? null : ArticleGroupType
                .valueOf(articleGroupType));
        if (model.getArticleGroupType() != null) {
            ArticleGroup abyId = serviceFactory.getPersistService().get(ArticleGroup.class, id);
            ArticleGroup abyType = serviceFactory.getArticleGroupSerivce().getArticleByGroupType(
                    ArticleGroupType.valueOf(articleGroupType));
            if (abyId.getArticleGroupType() == null && abyType != null) {
                return PageHandlerUtil.returnError(map, "新闻类型{" + model.getArticleGroupType().getText()
                        + "}对应的新闻不能有重复!");
            } else if ((abyId.getArticleGroupType() != null)
                    && (!abyId.getArticleGroupType().toString().equals(articleGroupType)) && abyType != null) {
                return PageHandlerUtil.returnError(map, "新闻类型{" + model.getArticleGroupType().getText()
                        + "}对应的新闻不能有重复!");
            }
        }
        ServiceResult<ArticleGroup> result = new ServiceResult<ArticleGroup>();
        try {
            result = serviceFactory.getArticleGroupSerivce().update(model);
            return returnSuccess(map, result, "/gm/list");
        } catch (Exception ex) {
            ex.printStackTrace();
            return returnError(map, ex);
        }
    }

    @RequestMapping(value = "/remove")
    public String delete(ModelMap map, HttpServletRequest request, Long[] ids) {
        if (ids == null || ids.length <= 0) {
            return returnError(map, "要删除的分组不能为空");
        }
        Long groupExCount = serviceFactory.getArticleGroupSerivce().countArticleGroupEx(ids, null);
        if (groupExCount.intValue() > 0) {
            return returnError(map, "您删除的分组中存在关联新闻，不能删除！");
        }
        try {
            Set<Object> set = new HashSet<Object>(Arrays.asList(ids));
            ServiceResult<ArticleGroup> result = serviceFactory.getArticleGroupSerivce().delete(set);
            return returnSuccess(request, map, result, "/gm/list");
        } catch (Exception ex) {
            ex.printStackTrace();
            return returnError(map, ex);
        }
    }

    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request, ModelMap map, String name, String remark) {
        /** 保存表单 */
        map.put("name", name);
        map.put("remark", remark);
        Pagination page = new Pagination(request);
        page.setPageSize(this.getPageSize(request));
        try {
            LinkedHashMap<String, OrderType> sortMap = new LinkedHashMap<String, OrderType>();
            sortMap.put("id", OrderType.DESC);
            List<ArticleGroup> list = serviceFactory.getArticleGroupSerivce()
                    .findArticleGroupPage(name, remark, page.currentPage, page.pageSize, sortMap).getReturnValue();
            Long count = serviceFactory.getArticleGroupSerivce().findArticleGroupCount(name).getReturnValue();
            page.setEntityCount(count.intValue());
            map.put("articleGroupList", list);
            map.put("articleGroupListPage", page);
            return "/article/group/groupmanage";
        } catch (Exception ex) {
            ex.printStackTrace();
            return returnError(map, ex);
        }
    }

    @RequestMapping(value = "/get/{id}")
    public ModelAndView get(@PathVariable Long id, ModelMap map) {
        if (id == null) {
            return new ModelAndView(returnError(map, "分组ID不能为空"));
        }
        try {
            ArticleGroup articleGroup = serviceFactory.getPersistService().get(ArticleGroup.class, id);
            ModelAndView modelAndView = new ModelAndView("/article/group/detail");
            modelAndView.addObject("group", articleGroup);
            return modelAndView;
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ModelAndView(returnError(map, ex));
        }
    }
}
